package com.coffee.excel.builder;

import com.coffee.excel.metadata.MochaExcelField;
import com.coffee.excel.metadata.MochaMergeRow;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: songkui
 * @since: 2023/2/14 11:01
 */
public class BasicExcelBuilder {


    /**
     * 将 前端传来的 字段 排序 添加列序号
     * @param fieldList List<MochaExcelField>
     */
    public void setColumnIndex(List<MochaExcelField> fieldList){
        fieldList.sort(Comparator.comparing(MochaExcelField::getFieldSort));
        int index =0;
        for (MochaExcelField mochaExcelFieldData : fieldList){
            mochaExcelFieldData.setColumnIndex(index);
            ++index;
        }
    }


    public  List<String> headShow(List<MochaExcelField> list){
        return list.stream().map(MochaExcelField::getHeadShow).collect(Collectors.toList());
    }

    public  Map<Integer, Short> headColorMap(List<MochaExcelField> list){
        return list.stream().filter(f -> f.getForegroundColor() != null && f.getForegroundColor() >0).collect(Collectors.toMap(MochaExcelField::getColumnIndex, MochaExcelField::getForegroundColor));
    }

    public  List<List<String>> exportTemplateData(List<MochaExcelField> list){
        List<List<String>> dataList = new ArrayList<>(1);
        dataList.add(list.stream().map(f -> String.format("{.%s}", f.getFieldValue())).collect(Collectors.toList()));
        return dataList;
    }

    public  List<CellRangeAddress> mergeAddressList(List<MochaExcelField> list){
        List<CellRangeAddress> mergeList = new ArrayList<>();
        for (MochaExcelField field : list){
            List<MochaMergeRow> mergeRows = field.getMergeRows();
            if (null == mergeRows || mergeRows.isEmpty()){
                continue;
            }
            for (MochaMergeRow row : mergeRows){
                mergeList.add(new CellRangeAddress(row.getFirstRow(),row.getLastRow(),field.getColumnIndex(),field.getColumnIndex()));
            }
        }
        return mergeList;
    }



}
